
Promise.all = function (values) {
    if (!Array.isArray(values)) {
        const type = typeof values;
        return new TypeError(`TypeError: ${type} ${values} is not iterable`)
    }

    return new Promise((resolve, reject) => {
        let resultArr = [];
        let orderIndex = 0;
        const processResultByKey = (value, index) => {
            resultArr[index] = value;
            if (++orderIndex === values.length) {
                resolve(resultArr)
            }
        }
        for (let i = 0; i < values.length; i++) {
            let value = values[i];
            if (value && typeof value.then === 'function') {
                value.then((value) => {
                    processResultByKey(value, i);
                }, reject);
            } else {
                processResultByKey(value, i);
            }
        }
    });
}


Promise.race = function (promises) {
    return new Promise((resolve, reject) => {
        // 一起执行就是for循环
        for (let i = 0; i < promises.length; i++) {
            let val = promises[i];
            if (val && typeof val.then === 'function') {
                val.then(resolve, reject);
            } else { // 普通值
                resolve(val)
            }
        }
    });
}
